package pers.lxl.design.thread;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * @describe: 一个家庭平分(同时)来数1亿粒米(使用线程池)
 * @author: lxl
 * @date: 2018/10/21 19:14
 * @version: v1.0
 */
public class FamilyCounter implements Counter {
    /**
     * 家庭成员(线程数量)
     */
    private int familyNumber;

    private ExecutorService pool;


    public FamilyCounter(int familyNumber) {
        this.familyNumber = familyNumber;
        this.pool = Executors.newFixedThreadPool(this.familyNumber);
    }

    @Override
    public long count(double[] riceArray) {
        long result = 0L;
        ArrayList<Future<Long>> results = new ArrayList<>();
        int part = riceArray.length / familyNumber;
        for (int i = 0; i < familyNumber; i++) {
            results.add(pool.submit(new CounterRiceTask(riceArray, i * part, (i + 1) * part)));
        }

        pool.shutdown();

        for (Future<Long> longFuture : results) {
            try {
                result += longFuture.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private static class CounterRiceTask implements Callable<Long> {
        private double[] riceArray;
        private int from;
        private int to;

        public CounterRiceTask(double[] riceArray, int from, int to) {
            this.riceArray = riceArray;
            this.from = from;
            this.to = to;
        }

        @Override
        public Long call() throws Exception {
            long total = 0L;

            for (int i = from; i <= to; i++) {
                if (riceArray[i] == 1) {
                    total += 1;
                }
                if (total >= 10000000) {
                    break;
                }
            }
            return total;
        }
    }
}
